package cn.shop.front.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.shop.front.entity.gamebind.MerchantAlias;
import cn.shop.front.service.BackSettingService;
import cn.shop.front.service.GameBindService;
import cn.shop.front.service.MediaService;
import cn.shop.front.util.AliasUtil;
import cn.shop.front.util.CurrentUserUtil;
import cn.shop.thiredparty.entity.SmsSendResult;
import cn.shop.thiredparty.entity.SmsSendStatus;
import cn.shop.thiredparty.service.ThiredpartyService;
import cn.shop.transcation.backSetting.entity.BackSetting;
import cn.shop.utils.ApiCode;
import cn.shop.utils.ApiResult;
import cn.shop.utils.Putif;
import cn.shop.utils.constant.Constant;
import cn.shop.utils.constant.SMSVerificationCode;
import cn.shop.utils.constant.SystemSettingConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 获取短信验证码
 *
 * @author : 李一涵
 * @date : Created in 2022-2-21 11:21
 * @description :
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/common")
public class CommonController {

	@Resource
	private BackSettingService backSettingService;

	@Resource
	private ThiredpartyService thiredpartyService;

	@Resource
	private GameBindService gameBindService;

	@Resource
	private MediaService mediaService;

	private static final int EXPIRE_MIN = 5;

	/**
	 * 获取服务协议
	 *
	 * @return 所有数据
	 * @author 痴
	 * @since 2022-05-18 23:40:27
	 */
	@GetMapping("queryServiceAgreement")
	public ApiResult<BackSetting> queryServiceAgreement() {
		BackSetting serviceAgreement = backSettingService.findByKey(SystemSettingConstant.SERVICE_AGREEMENT);
		return ApiResult.success(serviceAgreement);
	}

	/**
	 * 获取服务协议
	 *
	 * @return 所有数据
	 * @author 痴
	 * @since 2022-05-18 23:40:27
	 */
	@GetMapping("queryPrivacyPolicy")
	public ApiResult<BackSetting> queryPrivacyPolicy() {
		BackSetting serviceAgreement = backSettingService.findByKey(SystemSettingConstant.PRIVACY_POLICY);
		return ApiResult.success(serviceAgreement);
	}

	/**
	 * 通过手机号获取验证码
	 *
	 * @param map 手机号
	 * @return 验证码
	 */
	@PostMapping("/sms/verification")
	public ApiResult<Map<String, Object>> smsVerification(@RequestBody Map<String, String> map) {
		String code = RandomUtil.randomNumbers(6);
		SmsSendResult result = thiredpartyService.sendSms(code, EXPIRE_MIN, map.get("mobile"));
		log.info("验证码返回结果：{}", result);
		if (result != null && result.getStatus() == SmsSendStatus.OK) {
			long userId = CurrentUserUtil.getUserId();
			String key = Constant.SMS_CODE;
			if (userId != 0) {
				key = key + userId;
			}
			else {
				key = key + map.get("mobile");
			}
			SaSession session = SaSessionCustomUtil.getSessionById(key);
			session.set("code", code);
			session.updateTimeout(EXPIRE_MIN * 60);
			return ApiResult.success("验证码发送成功");
		}
		else {
			return ApiResult.fail("验证码发送失败");
		}
	}

	/**
	 * 通过手机号获取验证码
	 *
	 * @param map 手机号
	 * @return 验证码
	 */
	@PostMapping("/regist/verification")
	public ApiResult<Map<String, Object>> registVerification(@RequestBody Map<String, String> map) {
		String code = RandomUtil.randomNumbers(6);
		SmsSendResult result = thiredpartyService.sendSms(code, EXPIRE_MIN, map.get("mobile"));
		if (result != null && result.getStatus() == SmsSendStatus.OK) {
			String key = SMSVerificationCode.REGIST_KEY + map.get("mobile");
			SaSession session = SaSessionCustomUtil.getSessionById(key);
			session.set("code", code);
			session.updateTimeout(EXPIRE_MIN * 60);
			return ApiResult.success("验证码发送成功");
		}
		else {
			return ApiResult.fail("验证码发送失败");
		}
	}

	/**
	 * 检查域名是否可用
	 *
	 * @param request
	 * @return
	 */
	@GetMapping("/checkalias")
	public ApiResult<Map<String, Object>> checkAlias(HttpServletRequest request) {
		String domain = AliasUtil.getAlias(request);
		if (StrUtil.equals("www", domain)) {
			return ApiResult.success();
		}
		MerchantAlias alias = gameBindService.checkAlias(domain);
		if (alias == null) {
			return ApiResult.fail(ApiCode.NOT_FOUND);
		}
		else if (alias.getState() == 0) {
			return ApiResult.fail("二级域名审核中，请稍后访问");
		}
		else if (alias.getState() == 2) {
			return ApiResult.fail("二级域名审核未通过，请联系管理员");
		}
		Long count = gameBindService.checkLogin(alias.getUid(), LocalDateTime.now().plusMonths(-3));
		/*if (count <= 0) {
			return ApiResult.fail(ApiCode.NOT_USER);
		}*/
		return ApiResult.success();
	}

	/**
	 * 获取商户头部轮播公告
	 *
	 * @return
	 */
	@GetMapping("/getTopCarousel")
	public ApiResult<BackSetting> getTopCarousel() {
		return ApiResult.success(backSettingService.findByKey(SystemSettingConstant.SHOP_TOP_CAROUSEL));
	}

	/**
	 * 获取二级域名审核提示
	 *
	 * @return
	 */
	@GetMapping("/getDomainNameAudit")
	public ApiResult<BackSetting> getDomainNameAudit() {
		return ApiResult.success(backSettingService.findByKey(SystemSettingConstant.DOMAIN_NAME_AUDIT));
	}

	/**
	 * 获取公告
	 *
	 * @param request
	 * @return
	 */
	@GetMapping("/notices")
	public ApiResult<List<Map<String, Object>>> getNotices(HttpServletRequest request) {
		String domain = AliasUtil.getAlias(request);
		return ApiResult.success(mediaService.getNotices(domain));
	}

	/**
	 * 获取广告图
	 *
	 * @param request
	 * @return
	 */
	@GetMapping("/banners")
	public ApiResult<List<Map<String, Object>>> getBanners(HttpServletRequest request) {
		String domain = AliasUtil.getAlias(request);
		return ApiResult.success(mediaService.getBanners(domain));
	}

	/**
	 * 获取公告详情
	 *
	 * @param id 编号
	 * @return 返回结果
	 */
	@GetMapping("/notice/{id}")
	public ApiResult<Map<String, Object>> getNotice(@PathVariable long id) {
		return ApiResult.success(mediaService.getNoticeInfo(id));
	}

	/**
	 * 获取客服信息
	 *
	 * @param request
	 * @return
	 */
	@GetMapping("/service")
	public ApiResult<Map<String, Object>> getService(HttpServletRequest request) {
		String domain = AliasUtil.getAlias(request);
		return ApiResult.success(Putif.start().anyway("service", mediaService.getService(domain)).get());
	}

}
